﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OMBusiness;

namespace OpenMenu.Actions
{
    public abstract class BaseAction
    {
        protected readonly Form _baseForm ;
        protected ProgressForm _progressForm;
        private Form _msgForm;
        private bool _actionPause;
        protected ProgressController _ProgressController;

        public BaseAction()
        {
            _ProgressController = new ProgressController();
            _ProgressController.MessageChanged += OnControllerMessageChanged;
        }

        public BaseAction(Form baseForm) : this()
        {
            _baseForm = baseForm;
        }

        void OnControllerMessageChanged(string msg)
        {
           ProgressForm.ShowMessage(msg,_ProgressController.CanCancel);
        }

        public ProgressForm ProgressForm
        {
            get
            {
                if (_progressForm == null)
                {
                    _progressForm = new ProgressForm();
                    _progressForm.CancelClick += OnCancelClick;
                    _progressForm.HandleCreated += OnProgressFormCreated;
                }
                return _progressForm;
            }
        }

        private void OnProgressFormCreated(object sender, EventArgs e)
        {
            Thread thread = new Thread(RunActionAsync);
            thread.Start();
        }

        private void RunActionAsync()
        {
            try
            {
                Run();
                Thread.Sleep(2000);
                ProgressForm.CloseForm();
            }
            catch (Exception e)
            {
                ProgressForm.ShowError(e);
            }
        }

        public virtual void Run(){}

        public void RunInProgress()
        {
            if (_baseForm != null)
            {
                ProgressForm.ShowDialog(_baseForm);
            }
            else
            {
                ProgressForm.ShowDialog();
            }
        }

        private void OnCancelClick()
        {
            _ProgressController.CanCancel = true;
        }

        protected void ShowMessageForm(Form form)
        {
            _actionPause = true;
            _msgForm = form;
            _msgForm.Closed += OnMessageFormClosed;
            ProgressForm.Invoke(new Action(() => _msgForm.ShowDialog(ProgressForm)));
        }

        private void OnMessageFormClosed(object sender, EventArgs e)
        {
            _actionPause = false;
            _ProgressController.CanCancel = false;
        }
    }
}
